package com.it.a01udpdemo1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveMessageDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10086);

        //2.接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        //该方法是阻塞的
        //程序执行到这一步的时候，会在这里死等
        //等发送端发送消息
        System.out.println(1111);
        ds.receive(dp);
        System.out.println(2222);

        //3.解析数据
        byte[] data = dp.getData();
        int len = data.length;
        InetAddress address = dp.getAddress();
        int port = dp.getPort();

        System.out.println("接收到数据"+ new String(data,0,len));
        System.out.println("这数据是从"+address+"这台电脑中的"+port+"端口发出的");

        ds.close();
    }
}
